package com.hg.controller;

import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hg.common.HttpStatus;
import com.hg.common.R;
import com.hg.pojo.HgMallOrders;
import com.hg.pojo.HgMallShop;
import com.hg.service.HgHistoryOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/history")
@CrossOrigin
public class HgHistoryOrderController {

    @Autowired
    private HgHistoryOrderService hgHistoryOrderService;

    /**
     * 这在给到处表格做准备 提升一下状态
     */
    public static Page<HgMallOrders> hgMallOrdersPage;

    @Autowired
    private RedisTemplate redisTemplate;

    public static String key = null;

    /**
     * 查询历史订单
     * @param currentPage
     * @param pageSize
     * @param appid
     * @param orderNum
     * @param oddNum
     * @return
     */
    @GetMapping("/orderList")
    public R<Page<HgMallOrders>> getList(int currentPage, int pageSize,String appid,String orderNum,String oddNum,Long userId){
        Page<HgMallOrders> hgMallOrdersPage = null;
        key = "order_" + userId;
        redisTemplate.delete(key);
        hgMallOrdersPage = (Page<HgMallOrders>) redisTemplate.opsForValue().get(key);
        if(hgMallOrdersPage != null){
            return R.success(HttpStatus.ORDER_SUCCESS,hgMallOrdersPage);
        }
        hgMallOrdersPage = hgHistoryOrderService.selectHgMallOrdersList(currentPage, pageSize,appid,orderNum,oddNum,userId);
        if (hgMallOrdersPage!=null){
            redisTemplate.opsForValue().set(key,hgMallOrdersPage,60, TimeUnit.MINUTES);
            return R.success(HttpStatus.ORDER_SUCCESS,hgMallOrdersPage);
        }
        return R.error(HttpStatus.ORDER_ERROR,"查询错误");
    }

    /**
     * 修改状态
     * @param hgMallOrders
     * @return
     */
    @PutMapping("/updateStatus")
    public R<String> updateStatus(@RequestBody HgMallOrders hgMallOrders){
        LambdaUpdateWrapper<HgMallOrders> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(HgMallOrders::getStatus,hgMallOrders.getStatus());
        updateWrapper.eq(HgMallOrders::getId,hgMallOrders.getId());

        hgHistoryOrderService.update(updateWrapper);
        redisTemplate.delete(key);
        return R.success(HttpStatus.COMMON_SUCCESS,"修改成功");
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        Page<HgMallOrders> hgMallOrdersPage1 = hgMallOrdersPage;

        // 从数据库查询出所有的数据
        List<HgMallOrders> records = hgMallOrdersPage1.getRecords();

        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("appid", "用户");
        writer.addHeaderAlias("orderNum", "取单号");
        writer.addHeaderAlias("oddNum", "订单编号");
        writer.addHeaderAlias("status", "消费状态");
        writer.addHeaderAlias("priceAll", "总价");
        writer.addHeaderAlias("shopName", "所属店铺");


        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(records, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("历史订单表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }
}
